#include<iostream>
#include<string>
#include<cassert>
#include<cstdio>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

using namespace std;
int main()
{
    //1创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n!= -1);
    (void)n;
    #ifdef DEBUG
    cout<<"pipefd[0]"<<pipefd[0]<<endl;
    cout<<"pipefd[1]"<<pipefd[1]<<endl;
    #endif
    //创建子进程
    pid_t id = fork();
    if(id == 0)
    {
        //3构建单向通信
        close(pipefd[1]);

        char buffer[1024];
        while(true)
        {
            ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1 );
            if(s > 0)
            {
                buffer[s] = 0;
                cout<<"child get a message[" << getpid() << "]Father#"<< buffer << endl;
            }
        }

        exit(0);
    }
    //3.构建单向通信
    close(pipefd[0]);
    string message("我是父进程，我正在给你发消息");//这是发的消息
    char send_buffer[1024];
    int count = 0;
    while(true)
    {
        snprintf(send_buffer,sizeof(send_buffer), "%s[%d] : %d",message.c_str(), getpid(), count++ );
        write(pipefd[1], send_buffer, strlen(send_buffer));        //故意sleep(1)
        sleep(1);
       // cout<<send_buffer << endl;
    }

    //等子进程退出
    pid_t ret = waitpid(id, nullptr, 0);
    assert(ret < 0);
    (void)ret;
    close(pipefd[1]);
    return 0;
}
